use std::sync::{Arc, RwLock};
use std::thread;

fn main() {
    //创建一个共享的变量整数，使用RwLock包装
    let counter = Arc::new(RwLock::new(0));
    //创建一个多线程读取计数器
    // let mut read_handles = vec![];

    //创建一个线程持有读锁
    let read_handle = {
        let counter = counter.clone();
        thread::spawn(move || {
            //获取读锁
            let num = counter.read().unwrap();
            println!("Reader #1{:?}: {}", thread::current().id(), *num);
            //休眠模拟读操作
            thread::sleep(std::time::Duration::from_secs(10));
        })
    };


    //创建一个线程来写入计算器的值
    let write_handle = {
        let counter = counter.clone();
        thread::spawn(move || {
            //休眠一小段时间，取保读锁已经被获取
            thread::sleep(std::time::Duration::from_secs(1));
            //尝试获取写锁
            //等待会读锁会被释放
            let mut num = counter.write().unwrap();
            *num += 1;
            println!("Writer {:?}: Incremented counter to {}", thread::current().id(), *num);
        })
    };

    //创建一个线程请求读锁
    let read_handle_2 = {
        let counter = counter.clone();
        thread::spawn(move || {
            //休眠一小段时间，取保写锁已经被获取
            thread::sleep(std::time::Duration::from_secs(2));
            //尝试获取读锁
            let num = counter.read().unwrap();
            println!("Reader#2: {}", *num);
        })
    };


    //等待所有线程执行完成
    //等待写入线程完成
    read_handle.join().unwrap();
    write_handle.join().unwrap();
    read_handle_2.join().unwrap();
}
